using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Timers;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.View;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Text;
using Android.Text.Style;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Gcssloop.Widget;
using mb;
using mb.Droid;

namespace libmp
{
    public class RegisteredAccountView
    {
        static ILog logger = App.logger;
        static API.IStartOption startOption = App.StartOption;
        static StartActivity ctx = StartActivity.This;

        static EditText telphoneEdit;
        static EditText passwordEdit;
        static TextView telphoneTextView;
        static TextView passwordTextView;
        static TextView msgTextView;
        static EditText nickNameEdit;
        static EditText RegionalEdit;
        static EditText verificationEdit;

        static EditText confirmPasswordEdit;
        static TextView RegionalTextView;
        static TextView verificationTextView;

        static TextView confirmPasswordTextView;

        static TextView secondTextView;

        static TextView getVerificationButton;
        private static int second = 60;

        static MyFragment myFragment;
        public static MyFragment CreateFragment()
        {
            return myFragment = new MyFragment()
            {
                Title = "注册",
                MyOnCreateView = (f, container) => CreateView(f),
            };
        }

        public static View CreateView(MyFragment f)
        {
            ctx = StartActivity.This;
            LinearLayout FLayout = new LinearLayout(ctx);
            FLayout.Orientation = Orientation.Vertical;
            FLayout.SetBackgroundColor(Color.Rgb(238, 238, 238));

            FLayout.AddView(Common.CreateTitleBar(new Common.TitleBarOption() { Title = "注册" }));
            CreateContentView(FLayout);

            return FLayout;
        }

        public static void CreateContentView(ViewGroup FLayout)
        {
            LinearLayout msgTextViewLayout = new LinearLayout(FLayout.Context);
            var msgTextViewLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 100);
            msgTextViewLayout.LayoutParameters = msgTextViewLayoutParams;
            msgTextViewLayout.SetGravity(GravityFlags.Center);
            FLayout.AddView(msgTextViewLayout);
            msgTextView = new TextView(FLayout.Context);
            msgTextView.SetTextColor(Color.Rgb(251, 114, 153));
            msgTextView.SetTextSize(ComplexUnitType.Pt, 7);
            msgTextViewLayout.AddView(msgTextView);

            CreateEditText(FLayout, "昵称", nickNameEdit = new EditText(ctx), "请输入用户昵称", 0, false);

            FLayout.AddView(CreateCountrySelectButton().SetMarginEx(top: 5));

            CreateEditText(FLayout, "+86", telphoneEdit = new EditText(ctx), "请输入常用手机号", 25, true);
            CreateEditText(FLayout, "验证码", verificationEdit = new EditText(ctx), "请输入验证码", 1, false);
            CreateEditText(FLayout, "密码", passwordEdit = new EditText(ctx), "6~16个字符,区分大小写", 25, false);

            FLayout.AddView(
                Util.MakeFlatTextButton("立即注册").SetClickHandler((s, e) => OnRegisterClick()),
                new LinearLayout.LayoutParams(Util.dpToPx(200), Util.dpToPx(40)) { Gravity = GravityFlags.Center, TopMargin = 30, }
            );

            LinearLayout registeredLayoutBottom = new LinearLayout(ctx);
            var registeredLayoutBottomParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 120);
            registeredLayoutBottomParams.TopMargin = 80;
            registeredLayoutBottom.LayoutParameters = registeredLayoutBottomParams;
            registeredLayoutBottom.Orientation = Orientation.Horizontal;
            // registeredLayoutBottom.SetBackgroundColor(Color.Black);
            registeredLayoutBottom.SetGravity(GravityFlags.Center);
            registereAgreementViem(registeredLayoutBottom);

            if (startOption.GetBoolValue("autoFillRegInfo"))
            {
                nickNameEdit.Text = "测试用户";
                telphoneEdit.Text = "13512341234";
                verificationEdit.Text = "9527";
                passwordEdit.Text = "111111";
            }
        }

        async static Task < (string country, string code) > PickCountryCode(string initCountry)
        {
            var promise = new TaskCompletionSource < (string country, string code) > ();
            new CountryPickView(initCountry) { OnSelect = (n, c) => { promise.TrySetResult((n, c)); }, }
                .CreateFragment()
                .Show(ctx.SupportFragmentManager, "pickCountry");
            return await promise.Task;
        }

        static void registereAgreementViem(LinearLayout registeredLayoutBottom)
        {
            LinearLayout registeredLayoutBottomLeft = new LinearLayout(ctx);
            // registeredLayoutBottomLeft.SetBackgroundColor(Color.Red);
            registeredLayoutBottomLeft.SetVerticalGravity(GravityFlags.CenterVertical);
            var registereAgreement = new TextView(ctx);
            registereAgreement.Text = "点击“立即注册”按钮，即表示同意";
            registereAgreement.SetTextSize(ComplexUnitType.Pt, 7);
            registereAgreement.SetTextColor(Color.Black);
            registeredLayoutBottomLeft.AddView(registereAgreement);
            registeredLayoutBottom.AddView(registeredLayoutBottomLeft);

            LinearLayout registeredLayoutBottomRight = new LinearLayout(ctx);
            // registeredLayoutBottomRight.SetBackgroundColor(Color.Black);
            registeredLayoutBottomRight.SetVerticalGravity(GravityFlags.CenterVertical);
            var registereAgreementButton = new TextView(ctx);
            registereAgreementButton.Text = "  注册协议";
            registereAgreementButton.SetTextSize(ComplexUnitType.Pt, 7);
            registereAgreementButton.SetTextColor(Color.Blue);
            registeredLayoutBottomRight.Click += (s, e) =>
            {
                logger.Log("注册协议");
            };

            registeredLayoutBottomRight.AddView(registereAgreementButton);
            registeredLayoutBottom.AddView(registeredLayoutBottomRight);
        }

        static ViewGroup CreateCountrySelectButton()
        {
            var rootLayout = new LinearLayout(ctx);
            rootLayout.Orientation = Orientation.Horizontal;
            rootLayout.LayoutParameters = new LinearLayout.LayoutParams(-1, Util.dpToPx(50)) { TopMargin = 10, };
            rootLayout.Clickable = true;
            rootLayout.Click += async(s, e) =>
            {
                var tvCountry = rootLayout.GetChildAt(0) as TextView;
                var ret = await PickCountryCode(tvCountry.Text);
                logger.Log("click country", ret);
                tvCountry.Text = ret.country;
                tvPhonePrefix.Text = ret.code;
            };
            rootLayout.Background = Util.MakeDrawableSelector(new ColorDrawable(Color.White), new ColorDrawable(Color.White.Darker(0.9f)));
            rootLayout.SetVerticalGravity(GravityFlags.CenterVertical);

            rootLayout.AddView(
                new TextView(ctx) { Text = "中国大陆", Gravity = GravityFlags.CenterVertical }
                .SetTextSizeEx(ComplexUnitType.Dip, 20)
                .SetTextColorEx(Color.Black),
                new LinearLayout.LayoutParams(-1, -1, 1) { LeftMargin = 40, }
            );

            var imgs = 50;
            rootLayout.AddView(Util.MakeImageView("user/Fanhui1.png"), new LinearLayout.LayoutParams(imgs, imgs, 0) { RightMargin = Util.dpToPx(10) });

            return rootLayout;
        }

        static TextView tvPhonePrefix;
        static void CreateEditText(ViewGroup root, string editTexttitles, EditText editText, string editTextHint, int Margin, bool ifVerificationButton)
        {

            LinearLayout telphoneLayout = new LinearLayout(ctx);
            telphoneLayout.SetBackgroundColor(Color.White);
            var telphoneLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 120);
            telphoneLayout.LayoutParameters = telphoneLayoutParams;
            telphoneLayout.SetVerticalGravity(GravityFlags.CenterVertical);

            if (ifVerificationButton)
            {
                LinearLayout editTextTitleLayout = new LinearLayout(ctx);
                var editTextTitleLayoutParame = new LinearLayout.LayoutParams(190, LinearLayout.LayoutParams.MatchParent);
                editTextTitleLayoutParame.LeftMargin = 40;
                editTextTitleLayout.LayoutParameters = editTextTitleLayoutParame;
                editTextTitleLayout.SetVerticalGravity(GravityFlags.CenterVertical);
                var editTextTitleTextView = new TextView(ctx);
                tvPhonePrefix = editTextTitleTextView;

                editTextTitleLayout.AddView(editTextTitleTextView);
                editTextTitleTextView.Text = editTexttitles;
                editTextTitleTextView.SetTextColor(Color.Black);
                editTextTitleTextView.SetTextSize(ComplexUnitType.Pt, 8);
                telphoneLayout.AddView(editTextTitleLayout);

                var editTextParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 2);
                editTextParams.LeftMargin = -40;
                editTextParams.RightMargin = 45;
                editText.LayoutParameters = editTextParams;
                editText.SetBackgroundColor(Color.Rgb(204, 204, 204));
                editText.SetPadding(50, 2, 0, 0);
                editText.Background = null;
                editText.SetTextColor(Color.Rgb(30, 30, 30));
                editText.SetHintTextColor(Color.Rgb(204, 204, 204));
                editText.SetTextSize(ComplexUnitType.Pt, 7);
                editText.Hint = editTextHint;
                editText.Focusable = true;
                editText.SetSingleLine();
                telphoneLayout.AddView(editText);

                var verticalPix = new LinearLayout(ctx);
                var verticalPixParams = new LinearLayout.LayoutParams(2, 60);
                verticalPix.LayoutParameters = verticalPixParams;
                verticalPix.SetBackgroundColor(Color.Rgb(238, 238, 238));
                telphoneLayout.AddView(verticalPix);

                //验证码
                LinearLayout getVerificationButtonLayout = new LinearLayout(ctx);
                var getVerificationButtonParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
                getVerificationButtonLayout.LayoutParameters = getVerificationButtonParams;
                getVerificationButtonLayout.SetGravity(GravityFlags.Center);
                // getVerificationButtonLayout.SetVerticalGravity(GravityFlags.CenterVertical);
                createVerifyButton(getVerificationButtonLayout);
                telphoneLayout.AddView(getVerificationButtonLayout);

                getVerificationButton.Click += async(s, e) =>
                {
                    logger.Log("正在获取手机验证码");
                    initWrongMsg();
                    if (verifyTelephone() == true)
                    {
                        string telphoneString = telphoneEdit.Text;
                        var res = await User.me.Register(telphoneString, "", "", "");
                        if (res != null)
                            msgTextView.Text = res;
                        else
                        {
                            msgTextView.Text = res;
                            showVerifySecond(getVerificationButton);
                        }

                    }
                };

            }
            else
            {
                LinearLayout editTextTitleLayout = new LinearLayout(ctx);
                var editTextTitleLayoutParame = new LinearLayout.LayoutParams(190, LinearLayout.LayoutParams.MatchParent);
                editTextTitleLayoutParame.LeftMargin = 40;
                editTextTitleLayout.LayoutParameters = editTextTitleLayoutParame;
                editTextTitleLayout.SetVerticalGravity(GravityFlags.CenterVertical);
                var editTextTitleTextView = new TextView(ctx);

                editTextTitleLayout.AddView(editTextTitleTextView);
                editTextTitleTextView.Text = editTexttitles;
                editTextTitleTextView.SetTextColor(Color.Black);
                editTextTitleTextView.SetTextSize(ComplexUnitType.Dip, 14);
                telphoneLayout.AddView(editTextTitleLayout);

                var editTextParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
                editTextParams.LeftMargin = -40;
                editTextParams.RightMargin = 45;
                editText.LayoutParameters = editTextParams;
                editText.SetBackgroundColor(Color.Black);
                editText.SetBackgroundColor(Color.Rgb(204, 204, 204));
                editText.SetPadding(50, 2, 0, 0);
                editText.Background = null;
                editText.SetTextColor(Color.Rgb(30, 30, 30));
                editText.SetHintTextColor(Color.Rgb(204, 204, 204));
                editText.SetTextSize(ComplexUnitType.Pt, 7);
                editText.Hint = editTextHint;
                editText.Focusable = true;
                editText.SetSingleLine();
                telphoneLayout.AddView(editText);
            }

            var pix = new LinearLayout(ctx);
            var pixParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, Margin);
            pix.LayoutParameters = pixParams;
            pix.SetBackgroundColor(Color.Rgb(238, 238, 238));
            root.AddView(pix);
            root.AddView(telphoneLayout);
        }

        static LinearLayout GetVerificationButtonLayout;
        static LinearLayout secondTextViewLayout;
        private static void createVerifyButton(LinearLayout getVerificationButtonLayout)
        {
            getVerificationButton = new TextView(getVerificationButtonLayout.Context);
            getVerificationButton.SetTextColor(Color.Blue);
            getVerificationButton.Text = "获取验证码";

            getVerificationButtonLayout.AddView(getVerificationButton);

            secondTextView = new TextView(getVerificationButtonLayout.Context);
            secondTextView.SetTextColor(Color.Black);
            secondTextView.Text = second + "s";
            var lp = new LinearLayout.LayoutParams(111, 57);
            lp.LeftMargin = -111;
            secondTextView.LayoutParameters = lp;
            getVerificationButtonLayout.AddView(secondTextView);
            getVerificationButton.Alpha = 1;
            secondTextView.Alpha = 0;

        }

        private static void showVerifySecond(TextView getVerificationButton)
        {
            getVerificationButton.Alpha = 0;
            secondTextView.Alpha = 1;
            var testTimer = new Timer() { Interval = 1000, Enabled = true };
            testTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                if (second < 1)
                {
                    getVerificationButton.Alpha = 1;
                    secondTextView.Alpha = 0;
                    second = 60;
                    (sender as Timer).Stop();
                }
                secondTextView.Text = second + "s";
                second--;

            };
        }
        static async void OnRegisterClick()
        {
            logger.Log("注册了1");
            bool promptError = true;
            initWrongMsg();
            string nickNameString = nickNameEdit.Text;
            string EmailString = "";
            string telphoneString = telphoneEdit.Text;
            string verificationString = verificationEdit.Text;
            string passwordString = passwordEdit.Text;
            if (nickNameString.Length == 0)
            {
                msgTextView.Text = "昵称不能为空";
                promptError = false;
            }
            else if (nickNameString.Length > 12)
            {
                msgTextView.Text = "昵称不能大于12位";
                promptError = false;
            }
            else if (verifyTelephone() == false)
            {
                promptError = false;
            }
            else if (verificationString.Length == 0)
            {
                msgTextView.Text = "验证码不能为空";
                promptError = false;
            }
            else if (passwordString.Length < 6)
            {
                msgTextView.Text = "密码不能少于6位";
                promptError = false;
            }
            else if (passwordString.Length > 16)
            {
                msgTextView.Text = "密码不能大于16位";
                promptError = false;
            }

            if (promptError)
            {
                passwordString = Util.MD5Encrypt32(passwordString);
                var res = await User.me.Register(telphoneString, nickNameString, passwordString, verificationString);
                if (res != null)
                {
                    msgTextView.Text = res;
                    return;
                }

                logger.Log("注册成功--------------");
                second = 0;
                myFragment.FragmentManager.PopBackStack();
                MeView.LogIn();

            }

        }

        static bool verifyTelephone()
        {
            string telphoneString = telphoneEdit.Text;
            if (telphoneString.Length == 0)
            {
                msgTextView.Text = "请填写手机号码";
                return false;
            }
            else if (!Util.IsPhoneNo(telphoneString))
            {
                msgTextView.Text = "手机号码类型错误";
                return false;
            }
            return true;
        }

        static void initWrongMsg()
        {
            msgTextView.Text = "";
        }
        static string baseUrl = App.CurrentServerUrl;

    }
}